// app.js
const express = require('express');
// const Chat = require('./models/Chat');
const User = require('./models/User');
const app = express();

app.use(express.json());

// 路由
const chatRoutes = require('./routes/chat');
const uploadRoutes = require('./routes/upload');
const friendRoutes = require('./routes/friend');


const path = require('path');
app.use('/api/chat', chatRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/friend', friendRoutes);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/api/users/:userId/friends', async (req, res) => {
  const userId = req.params.userId;
  const friendList = await getFriendList(userId);
  res.json(friendList);
});


// GET /api/user/profile?userId=xxx
app.get('/api/user/profile', async (req, res) => {
  const user = await User.findOne({ userId: req.query.userId });
  if (!user) return res.status(404).json({ message: '用户不存在' });
  res.json({
    userId:   user.userId,
    nickname: user.nickname,
    email:    user.email,
    avatar:   user.avatar,
    gender:   user.gender,
    bio:      user.bio
  });
});

app.get('/api/user/profile/:userId', async (req, res) => {
  const user = await User.findOne({ userId: req.params.userId });
  if (!user) return res.status(404).json({ message: '用户不存在' });
  res.json({
    userId:   user.userId,
    nickname: user.nickname,
    email:    user.email,
    avatar:   user.avatar,
    gender:   user.gender,
    bio:      user.bio
  });
});

// PUT /api/user/profile
app.put('/api/user/profile', async (req, res) => {
  const { userId, nickname, email, avatar, gender, bio } = req.body;
  await User.updateOne({ userId }, { nickname, email, avatar, gender, bio });
  res.json({ success: true });
});

// PUT /api/user/password
app.put('/api/user/password', async (req, res) => {
  const { userId, oldPassword, newPassword } = req.body;
  const user = await User.findOne({ userId });
  if (!user || user.password !== oldPassword) {
    return res.status(400).json({ message: '原密码错误' });
  }
  user.password = newPassword;
  await user.save();
  res.json({ success: true });
});




module.exports = app;

